<!--
 * @Author: canlong.shen
 * @Date: 2025-08-19 16:47:31
 * @LastEditors: canlong.shen
 * @FilePath: \tianditu-01\src\BsgoalTianMapSearch.vue
 * @Description: 
-->

<script setup>
import { ref, computed, watch, onMounted, onUnmounted, markRaw, shallowRef } from "vue";

defineOptions({
  name: "BsgoalTianMapSearch",
});

const props = defineProps({
  width: {
    type: String,
    default: "800",
  },
  height: {
    type: String,
    default: "600",
  },
});

const model = defineModel();

// ---> S 初始化地图 <---

let map = null;
let marker = null;
let zoom = 12;
const TIAN_MAP_SEARCH_REF = ref(null);
const initMap = () => {
  const mapEl = TIAN_MAP_SEARCH_REF.value;

  map = markRaw(new T.Map(mapEl), {});

  map.centerAndZoom(new T.LngLat(116.40769, 39.89945), zoom);
  //创建比例尺控件对象
  const scale = new T.Control.Scale();
  //添加比例尺控件
  map.addControl(scale);
  //创建缩放平移控件对象
  const ZooCcontrol = new T.Control.Zoom();
  //添加缩放平移控件
  map.addControl(ZooCcontrol);

  const point = new T.LngLat(116.400244, 39.92556);
  marker = new T.Marker(point, {
    draggable: true,
  }); // 创建标注
  initMarkerEvent();
  map.addOverLay(marker);
  getLocation();
  initLocalSearchResult();
  initMapMoveEvent();
};

const getLocation = () => {
  if (!navigator.geolocation) {
    ElMessage.error("浏览器不支持地理位置服务");
    return;
  }
  navigator.geolocation.getCurrentPosition(
    (position) => {
      const centerMarker = [position.coords.longitude, position.coords.latitude];
      const LngLat = new T.LngLat(centerMarker[0], centerMarker[1]);
      marker.setLngLat(LngLat);
      map.panTo(LngLat, 24);
      returnLngLat();
      console.log("【map】centerMarker", centerMarker);
    },
    (err) => {
      ElMessageBox.alert("请开启浏览器/电脑位置服务！");
    }
  );
};

onMounted(() => {
  initMap();
});

const wrapStyleGet = computed(() => {
  const { width, height } = props || {};
  return {
    width: `${width}px`,
    height: `${height}px`,
  };
});

// ---> E 初始化地图 <---

// ---> S 初始marker 的事件 <---

const markerDragend = (e) => {
  const lnglat = e.target.getLngLat();
  console.log("【marker】dragend", lnglat.getLng(), lnglat.getLat());
  returnLngLat();
};

const initMarkerEvent = () => {
  marker.removeEventListener("dragend", markerDragend);
  marker.addEventListener("dragend", markerDragend);
};

// ---> E 初始marker 的事件 <---

// ---> S 拖动地图的时候改变Marker坐标 <---

const mapClick = () => {
  curPoisList.value = [];
  inputSearchText.value = "";
};

const addMapClickEvent = () => {
  map.removeEventListener("click", mapClick);
  map.addEventListener("click", mapClick);
};

const MapMoveend = (e) => {
  console.log("【map】moveend", e);
  const center = e.target.getCenter();
  marker.setLngLat(center);
  console.log("【map】center", center.getLng(), center.getLat());
  if (e.type === "moveend") {
    returnLngLat();
  }
};

const removeMapMoveend = () => {
  map.removeEventListener("move", MapMoveend);
  map.removeEventListener("moveend", MapMoveend);
};

const addMapMoveend = () => {
  removeMapMoveend();
  map.addEventListener("move", MapMoveend);
  map.addEventListener("moveend", MapMoveend);
};

const initMapMoveEvent = () => {
  addMapMoveend();
  addMapClickEvent();
};

// ---> E 拖动地图的时候改变Marker坐标 <---

// ---> S 地址搜索 <---
const inputSearchText = ref("");
let searchTimeOut = null;
const searchValueChange = () => {
  console.log("【search】value", inputSearchText.value);
  const inputSearchTextValue = inputSearchText.value;

  if (!inputSearchTextValue) {
    curPoisList.value = [];
    return;
  }

  if (searchTimeOut) {
    clearTimeout(searchTimeOut);
  }

  searchTimeOut = setTimeout(() => {
    localsearch.search(inputSearchTextValue);
  }, 500);
};

const curPoisList = shallowRef([]);
const localSearchResult = (result) => {
  console.log("搜索结果", result);
  console.log("搜索结果", result.getPois());

  const poisList = result.getPois() || [];

  if (poisList.length) {
    if (!inputSearchText.value) {
      curPoisList.value = [];
    } else {
      curPoisList.value = poisList;
    }

    //     {
    //     "address": "光明区光明街道白花社区第二工业区博思高科技大厦",
    //     "phone": "",
    //     "poiType": "101",
    //     "name": "深圳博思高公司",
    //     "source": "0",
    //     "hotPointID": "41DC61829513115E",
    //     "lonlat": "113.977338,22.731748"
    // }
  } else {
    curPoisList.value = [];
  }
};

const clickPoisItem = (pois = {}) => {
  const { name, address, lonlat } = pois;
  const [lng, lat] = lonlat.split(",") || [];
  console.log("点击搜索结果", lng, lat);
  const LngLat = new T.LngLat(lng, lat);
  map.panTo(LngLat, 24);
  marker.setLngLat(LngLat);
  returnLngLat();
};

let localsearch = null;
const initLocalSearchResult = () => {
  const config = {
    pageCapacity: 5, //每页显示的数量
    onSearchComplete: localSearchResult, //接收数据的回调函数
  };
  //创建搜索对象
  localsearch = new T.LocalSearch(map, config);
};

// ---> E 地址搜索 <---

// ---> S 返回经纬度   <---

const returnLngLat = () => {
  const lnglat = marker.getLngLat();
  const lnglatStr = `${lnglat.getLng()},${lnglat.getLat()}`;
  model.value = lnglatStr;

  console.log("【marker】returnLngLat", lnglatStr);
};

// ---> E 返回经纬度   <---
</script>
<template>
  <div class="bsgoal-tian-map-search" :style="wrapStyleGet">
    <div ref="TIAN_MAP_SEARCH_REF" :style="wrapStyleGet"></div>
    <div class="map_search_container">
      <input
        type="text"
        v-model="inputSearchText"
        @input="searchValueChange"
        class="search_input"
        placeholder="输入关键字选取地点"
      />

      <div>
        <template v-for="pois in curPoisList">
          <div @click="clickPoisItem(pois)" class="search_item">
            <div class="search_item_name">{{ pois.name }}</div>
            <div class="search_item_address">{{ pois.address }}</div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>
<style scoped>
.bsgoal-tian-map-search {
  position: relative;
}

.map_search_container {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 999999999;
  width: 200px;
  background-color: white;
  margin: 16px;
}
.search_input {
  width: 192px;
  height: 20px;
}
.search_item {
  width: 100%;
  cursor: pointer;
  margin: 0 4px;
  border-bottom: 1px solid #eee;
}
.search_item_name {
  color: rgb(96, 98, 102);
  font-size: 14px;
  line-height: 32px;
  overflow-wrap: break-word;
}

.search_item_address {
  color: rgb(153, 153, 153);
  font-size: 12px;
  line-height: 32px;
}
</style>
